package com.juhe.weather;

import android.app.Activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;


import com.juhe.weather.bean.FutureWeatherBean;
import com.juhe.weather.bean.HoursWeatherBean;
import com.juhe.weather.bean.WeatherBean;
import com.juhe.weather.swiperefresh.PullToRefreshBase;
import com.juhe.weather.swiperefresh.PullToRefreshScrollView;
import com.juhe.weather.tool.PureNetUtil;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


/**
 * Created by LiuLin on 2017/2/27.
 */

public class WeatherActivity extends Activity {
    private PullToRefreshScrollView n;
    private ScrollView m;
    private TextView tv_city,// 城市
            tv_release,// 发布时间
            tv_now_weather,// 天气
            tv_today_temp,// 温度
            tv_now_temp,// 当前温度
            tv_aqi,// 空气质量指数
            tv_quality,// 空气质量
            tv_next_three,// 3小时
            tv_next_six,// 6小时
            tv_next_nine,// 9小时
            tv_next_twelve,// 12小时
            tv_next_fifteen,// 15小时
            tv_next_three_temp,// 3小时温度
            tv_next_six_temp,// 6小时温度
            tv_next_nine_temp,// 9小时温度
            tv_next_twelve_temp,// 12小时温度
            tv_next_fifteen_temp,// 15小时温度
            tv_today_temp_a,// 今天温度a
            tv_today_temp_b,// 今天温度b
            tv_tommorrow,// 明天
            tv_tommorrow_temp_a,// 明天温度a
            tv_tommorrow_temp_b,// 明天温度b
            tv_thirdday,// 第三天
            tv_thirdday_temp_a,// 第三天温度a
            tv_thirdday_temp_b,// 第三天温度b
            tv_fourthday,// 第四天
            tv_fourthday_temp_a,// 第四天温度a
            tv_fourthday_temp_b,// 第四天温度b
            tv_humidity,// 湿度
            tv_wind,
            tv_uv_index,// 紫外线指数
            tv_dressing_index;// 穿衣指数
    private ImageView iv_now_weather,// 现在
            iv_next_three,// 3小时
            iv_next_six,// 6小时
            iv_next_nine,// 9小时
            iv_next_twelve,// 12小时
            iv_next_fifteen,// 15小时
            iv_today_weather,// 今天
            iv_tommorrow_weather,// 明天
            iv_thirdday_weather,// 第三天
            iv_fourthday_weather;// 第四天


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            setViews((WeatherBean)msg.obj);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        init();


        new Thread(new Runnable() {

            @Override
            public void run() {
                WeatherBean hbean = GetTodayTemperatureByCity("葫芦岛");
//                WeatherBean h3=GetFutureThreeHours("西安");
                Message message = Message.obtain();
                message.obj = hbean;
                handler.sendMessage(message);
            }
        }
        ).start();

//        WeatherBean hbean = GetTodayTemperatureByCity("北京");
//        setViews(hbean);
    }

    private void init() {
        n = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview);
        n.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {

            }
        });
        m = n.getRefreshableView();
        tv_city = (TextView) findViewById(R.id.tv_city);
        tv_release = (TextView) findViewById(R.id.tv_release);
        tv_now_weather = (TextView) findViewById(R.id.tv_now_weather);
        tv_today_temp = (TextView) findViewById(R.id.tv_today_temp);
        tv_now_temp = (TextView) findViewById(R.id.tv_now_temp);
        tv_aqi = (TextView) findViewById(R.id.tv_aqi);
        tv_quality = (TextView) findViewById(R.id.tv_quality);
        tv_next_three = (TextView) findViewById(R.id.tv_next_three);
        tv_next_six = (TextView) findViewById(R.id.tv_next_six);
        tv_next_nine = (TextView) findViewById(R.id.tv_next_nine);
        tv_next_twelve = (TextView) findViewById(R.id.tv_next_twelve);
        tv_next_fifteen = (TextView) findViewById(R.id.tv_next_fifteen);
        tv_next_three_temp = (TextView) findViewById(R.id.temp_next_three);
        tv_next_six_temp = (TextView) findViewById(R.id.temp_next_six);
        tv_next_nine_temp = (TextView) findViewById(R.id.temp_next_nine);
        tv_next_twelve_temp = (TextView) findViewById(R.id.temp_next_twelve);
        tv_next_fifteen_temp = (TextView) findViewById(R.id.temp_next_fifteen);
        tv_today_temp_a = (TextView) findViewById(R.id.tv_today_temp_a);
        tv_today_temp_b = (TextView) findViewById(R.id.tv_today_temp_b);
        tv_tommorrow = (TextView) findViewById(R.id.tv_tommorrow);
        tv_tommorrow_temp_a = (TextView) findViewById(R.id.tv_tommorrow_temp_a);
        tv_tommorrow_temp_b = (TextView) findViewById(R.id.tv_tommorrow_temp_b);
        tv_thirdday = (TextView) findViewById(R.id.tv_thirdday);
        tv_thirdday_temp_a = (TextView) findViewById(R.id.tv_thirdday_temp_a);
        tv_thirdday_temp_b = (TextView) findViewById(R.id.tv_thirdday_temp_b);
        tv_fourthday = (TextView) findViewById(R.id.tv_fourthday);
        tv_fourthday_temp_a = (TextView) findViewById(R.id.tv_fourthday_temp_a);
        tv_fourthday_temp_b = (TextView) findViewById(R.id.tv_fourthday_temp_b);

        tv_humidity = (TextView) findViewById(R.id.tv_humidity);
        tv_wind = (TextView) findViewById(R.id.tv_wind);
        tv_uv_index = (TextView) findViewById(R.id.tv_uv_index);
        tv_dressing_index = (TextView) findViewById(R.id.tv_dressing_index);

        iv_now_weather = (ImageView) findViewById(R.id.iv_now_weather);
        iv_next_three = (ImageView) findViewById(R.id.iv_next_three);
        iv_next_six = (ImageView) findViewById(R.id.iv_next_six);
        iv_next_nine = (ImageView) findViewById(R.id.iv_next_nine);
        iv_next_twelve = (ImageView) findViewById(R.id.iv_next_twelve);
        iv_next_fifteen = (ImageView) findViewById(R.id.iv_next_fifteen);
        iv_today_weather = (ImageView) findViewById(R.id.iv_today_weather);
        iv_tommorrow_weather = (ImageView) findViewById(R.id.iv_tommorrow_weather);
        iv_thirdday_weather = (ImageView) findViewById(R.id.iv_thirdday_weather);
        iv_fourthday_weather = (ImageView) findViewById(R.id.iv_fourthday_weather);
    }

    public String excute(String cityName) {
        try {
            cityName = URLEncoder.encode(cityName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.w("test", cityName);
        String url =//此处以返回json格式数据示例,所以format=2,以根据城市名称为例,cityName传入中文
                "http://v.juhe.cn/weather/index?cityname=" + cityName + "&key=4c9f0ddced39015a8ff47b4287eeaa09";
        return PureNetUtil.get(url);//通过工具类获取返回数据
    }

    /**
     * 获取返回数据中的一个属性示例,此处以获取今日温度为例
     * "temperature": "8℃~20℃"     今日温度
     *
     * @param
     * @return
     */
    public WeatherBean GetTodayTemperatureByCity(String city) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        WeatherBean bean = new WeatherBean();
        String jsonString = excute(city);
        Log.w("test", jsonString);
        if (jsonString != null) {
            try {
                JSONObject resultJson = new JSONObject(jsonString);
                Log.w("test", "GetTodayTemperatureByCity: ." + resultJson.toString());
            /*获取返回状态码*/
                String resultcode = resultJson.getString("resultcode");
            /*如果状态码是200说明返回数据成功*/
                if (resultcode != null && resultcode.equals("200")) {
                    //此时result中数据有多个key,可以对其key进行遍历,得到对个属性
                    JSONObject json = resultJson.getJSONObject("result");
                    //今日温度对应的key是today
                    JSONObject TodayJson = json.getJSONObject("today");
                    bean.setCity(TodayJson.getString("city"));
                    bean.setUv_index(TodayJson.getString("uv_index"));
                    bean.setTemp(TodayJson.getString("temperature"));
                    bean.setWeather_str(TodayJson.getString("weather"));
                    bean.setWeather_id(TodayJson.getJSONObject("weather_id").getString("fa"));
                    Log.v("test",bean.getWeather_id());
                    bean.setDressing_index(TodayJson.getString("dressing_index"));
                    bean.setWind(TodayJson.getString("wind"));
                    //SK
                    JSONObject SkJson = json.getJSONObject("sk");
                    bean.setHumidity(SkJson.getString("humidity"));
                    bean.setWind(SkJson.getString("wind_direction") + "  " + SkJson.getString("wind_strength"));
                    bean.setNow_temp(SkJson.getString("temp"));
                    bean.setRelease(SkJson.getString("time"));
                    //future
//                    String future=json.getString("future");
//                    Log.v("test",future);
//                    JSONArray futureArray = json.getJSONArray("future");

//                    JSONArray f=json.getJSONArray("future");
//                    JSONObject  J=f.getJSONObject(0);
//                    Log.v("test",J.getString("temperature"));
//                    List<FutureWeatherBean> futureList = new ArrayList<FutureWeatherBean>();
//                    for (int i = 0; i < futureArray.length(); i++) {
//                        try {
//                            JSONObject futureJson = futureArray.getJSONObject(i);
//                            FutureWeatherBean futureWeatherBean = new FutureWeatherBean();
//                            futureWeatherBean.setTemp(futureJson.getString("temperature"));
//                            futureWeatherBean.setWeek(futureJson.getString("week"));
//                            futureWeatherBean.setWeather_id(futureJson.getJSONObject("weather_id").getString("fa"));
//                            Date date = new Date(System.currentTimeMillis());
//                            Date datef = sdf.parse(futureJson.getString("date"));
//                            if (!datef.after(date)) {
//                                continue; //结束单次循环
//                            }
//                            futureList.add(futureWeatherBean);
//                            if (futureList.size() == 3) {
//                                break;//结束整个循环体
//                            }
//
//                        } catch (ParseException e) {
//                            e.printStackTrace();
//                        }
//
//
//                    }
//                    bean.setFutureList(futureList);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        String f3Json=f3hexcute(city);
        if(f3Json!=null) {
            try {
                JSONObject json = new JSONObject(f3Json);
                String resultcode = json.getString("resultcode");
                if (resultcode.equals("200")) {
                    JSONArray f3Array = json.getJSONArray("result");
                    List<HoursWeatherBean> list = new ArrayList<>();
                    Log.v("test2", String.valueOf(f3Array.length()));
                    for (int i = 0; i < f3Array.length(); i++) {
                        HoursWeatherBean hoursWeatherBean = new HoursWeatherBean();
                        JSONObject jsonf3 = f3Array.getJSONObject(i);
                        hoursWeatherBean.setWeather_id(jsonf3.getString("weatherid"));
                        hoursWeatherBean.setTemp(jsonf3.getString("temp2") + "°" + "~" + jsonf3.getString("temp1") + "°");
                        hoursWeatherBean.setTime(jsonf3.getString("sh"));
                        list.add(hoursWeatherBean);
                        if (list.size() == 5) {
                            break;
                        }
                    }
                    bean.setGetH3List(list);
                    for (HoursWeatherBean s : list) {
                        Log.v("test2", s.getWeather_id() + "  " + s.getTemp() + "   " + s.getTime());
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        String pmResult=pmexcute(city);
        try {
            JSONObject pmJson=new JSONObject(pmResult);
            String resultcode=pmJson.getString("resultcode");
            if(resultcode.equals("200")){
                JSONArray pmArray=pmJson.getJSONArray("result");
                if(pmArray.length()==1) {
                    JSONObject piJson = pmArray.getJSONObject(0);
                    bean.setPm(piJson.getString("PM2.5"));
                    bean.setQuality(piJson.getString("quality"));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return bean;
    }

    private void setViews(WeatherBean bean) {
        tv_city.setText(bean.getCity());
        tv_release.setText(bean.getRelease());
        tv_now_temp.setText(bean.getNow_temp());
        tv_now_weather.setText(bean.getWeather_str());
        iv_now_weather.setImageResource(getResources().getIdentifier("d"+bean.getWeather_id(),"drawable","com.juhe.weather"));
        String[] tempArr = bean.getTemp().split("~");
//        String temp_str_a = tempArr[1].substring(0, tempArr[1].indexOf("C"));
//        String temp_str_b = tempArr[0].substring(0, tempArr[0].indexOf("C"));
        tv_today_temp.setText("↓ " +tempArr[0] + "  ↑" + tempArr[1]);
        iv_today_weather.setImageResource(getResources().getIdentifier("d" + bean.getWeather_id(), "drawable", "com.juhe.weather"));
        tv_today_temp_a.setText(tempArr[0]);
        tv_today_temp_b.setText(tempArr[1]);
        tv_wind.setText(bean.getWind());
        tv_dressing_index.setText(bean.getDressing_index());
        tv_uv_index.setText(bean.getUv_index());
        tv_humidity.setText(bean.getHumidity());
        List<HoursWeatherBean>  h3List=bean.getGetH3List();
        if(h3List.size()==5){
            setH3Views(tv_next_three,iv_next_three,tv_next_three_temp,h3List.get(0));
            setH3Views(tv_next_six,iv_next_six,tv_next_six_temp,h3List.get(1));
            setH3Views(tv_next_nine,iv_next_nine,tv_next_nine_temp,h3List.get(2));
            setH3Views(tv_next_twelve,iv_next_twelve,tv_next_twelve_temp,h3List.get(3));
            setH3Views(tv_next_fifteen,iv_next_fifteen,tv_next_fifteen_temp,h3List.get(4));
        }
        tv_aqi.setText(bean.getPm());
        tv_quality.setText(bean.getQuality());
//        List<FutureWeatherBean> list = bean.getFutureList();
//        tv_tommorrow.setText(list.get(0).getWeek());
//        if (list.size() == 3) {
//            setFutureViews(tv_tommorrow, iv_today_weather, tv_tommorrow_temp_a, tv_tommorrow_temp_b, list.get(0));
//            setFutureViews(tv_thirdday, iv_thirdday_weather, tv_thirdday_temp_a, tv_thirdday_temp_b, list.get(1));
//            setFutureViews(tv_fourthday, iv_fourthday_weather, tv_fourthday_temp_a, tv_fourthday_temp_b, list.get(2));
//        }

    }

//    private void setFutureViews(TextView tv_week, ImageView iv_weather, TextView tv_temp_a, TextView tv_temp_b, FutureWeatherBean bean) {
//        tv_week.setText(bean.getWeek());
//        iv_weather.setImageResource(getResources().getIdentifier("d" + bean.getWeather_id(), "drawable", "com.juhe.weather"));
//        String[] tempArr = bean.getTemp().split("~");
//        String temp_str_a = tempArr[1].substring(0, tempArr[1].indexOf("℃"));
//        String temp_str_b = tempArr[0].substring(0, tempArr[0].indexOf("℃"));
//        tv_today_temp_a.setText(temp_str_a + "°");
//        tv_today_temp_b.setText(temp_str_b + "°");
//
//    }

    public String f3hexcute(String cityName) {
        try {
            cityName = URLEncoder.encode(cityName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.w("test", cityName);
        String url =//此处以返回json格式数据示例,所以format=2,以根据城市名称为例,cityName传入中文
                "http://v.juhe.cn/weather/forecast3h.php?cityname=" + cityName + "&key=4c9f0ddced39015a8ff47b4287eeaa09";
        return PureNetUtil.get(url);//通过工具类获取返回数据
    }
    private void setH3Views(TextView tv_time,ImageView iv_weather,TextView tv_temp,HoursWeatherBean bean){
        tv_temp.setText(bean.getTemp());
        tv_time.setText(bean.getTime());
        iv_weather.setImageResource(getResources().getIdentifier("d"+bean.getWeather_id(),"drawable","com.juhe.weather"));
    }
    public String pmexcute(String cityName){
        try {
            cityName=URLEncoder.encode(cityName,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.w("test2",cityName);
        String url="http://web.juhe.cn:8080/environment/air/pm?city=" + cityName + "&key=33da71e2a8f8df79d6631f5d0693402f";
        return PureNetUtil.get(url);
    }
}

